package org.zhangyp.n02datastructure.n03Stack;

/**
 * 数组实现栈
 *
 * @author ypzhang
 * @since 2024/12/25
 */
public class MyArrayStack<E> implements MyStack<E> {
    private Object[] data = new Object[1];
    private int size;

    public MyArrayStack() {
    }
    // 数组初始容量
    public MyArrayStack(int cap) {
        data = new Object[cap];
    }

    @Override
    public void push(E item) {
        judgeSize();
        data[size++] = item;
    }

    private void judgeSize() {
        if (size >= data.length) {
            //扩容
            resize(data.length * 2);
        } else if (size > 0 && size < data.length / 2) {
            // 缩容
            resize(data.length / 2);
        }
    }

    private void resize(int newLength) {
        Object[] temp = new Object[newLength];
        // 复制数据到新数组
        for (int i = 0; i < size; i++) {
            temp[i] = data[i];
        }
        data = temp;
    }


    @Override
    public E pop() {
        if (isEmpty()) {
            return null;
        }
        // 这里原本是需要将最后一个元素返回，并清空最后一个元素，然后size减一，size--刚好是最后一个元素的下标，为了简洁所以这么写
        E res = (E) data[--size];
        data[size] = null; //释放已弹出的数据
        return res;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }
}
